package com.codi.api.controller.organ;

import com.codi.api.security.UserUtil;
import com.codi.base.domain.BaseResult;
import com.codi.base.exception.BaseAppException;
import com.codi.base.log.annotation.Loggable;
import com.codi.bus.core.domain.OrgFile;
import com.codi.bus.core.resultModel.OrganFileResult;
import com.codi.bus.core.service.EmailService;
import com.codi.bus.core.service.organ.OrgFileService;
import com.codi.superman.base.manager.FileUploadMgr;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangzhenhao on 2017/9/6.
 */
@Slf4j
@RestController
@RequestMapping("/organ/upload")
public class OrganUploadController {

    @Autowired
    private FileUploadMgr fileUploadMgr;

    @Autowired
    private OrgFileService orgFileService;

    @Autowired
    private EmailService emailService;

    @Loggable
    @PostMapping("input_user_email")
    public BaseResult inputUserEmail(String userEmail) {
        emailService.emailManage(userEmail);

        return BaseResult.success();
    }


    @Loggable
    @PostMapping("upload_organ_file")
    public BaseResult uploadOrganFile(OrganFileResult organFileResult) throws BaseAppException {
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }


    /**
     * 上传营业执照
     */
    @Loggable
    @RequestMapping(value = "upload_business_license", method = RequestMethod.POST)
    public BaseResult uploadBusinessLicense(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("businessLicense");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传组织机构代码证 organization code certificate
     */
    @RequestMapping(value = "upload_organization_code_certificate", method = RequestMethod.POST)
    public BaseResult uploadOrganizationCodeCertificate(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("organizationCodeCertificate");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传身份证 正面 ID Card
     */
    @Loggable
    @RequestMapping(value = "upload_identify_card_positive", method = RequestMethod.POST)
    public BaseResult uploadIdentifyCardPositive(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("identifyCard_positive");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    @Loggable
    @PostMapping("upload_signature_card")
    public BaseResult uploadSignatureCard(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("signature_card");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传身份证 背面 ID Card
     */
    @Loggable
    @RequestMapping(value = "upload_identify_card_back", method = RequestMethod.POST)
    public BaseResult uploadIdentifyCard(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("identifyCard_back");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传银行账户证明文件
     */
    @RequestMapping(value = "upload_bank_account_certificate", method = RequestMethod.POST)
    public BaseResult uploadBankAccountCertificate(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("bankAccountCertificate");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传经办人身份证 正面
     */
    @Loggable
    @RequestMapping(value = "upload_agent_identify_card_positive", method = RequestMethod.POST)
    public BaseResult uploadAgentIdentifyCardPositive(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("agentIdentifyCardPositive");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传经办人身份证 正面
     */
    @Loggable
    @RequestMapping(value = "upload_agent_identify_card_back", method = RequestMethod.POST)
    public BaseResult uploadAgentIdentifyCardBack(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("agentIdentifyCardBack");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 上传授权书
     */
    @Loggable
    @RequestMapping(value = "upload_authorization", method = RequestMethod.POST)
    public BaseResult uploadAuthorization(OrganFileResult organFileResult) throws BaseAppException{
        organFileResult.setFileType("authorization");
        Long userId = UserUtil.getLoginUserId();
        organFileResult.setUserId(userId);

        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 根据企业userId获取企业文件列表
     */
    @Loggable
    @RequestMapping(value = "get_company_files", method = RequestMethod.POST)
    public BaseResult getCompanyFiles(Long profileId) throws BaseAppException{
        Long userId = UserUtil.getLoginUserId();
//        Long userId = 4362L;

        List<OrganFileResult> organFileResults = orgFileService.queryFilesByUserIdAndProfileId(userId, profileId);

        if (organFileResults == null) {
            return BaseResult.success(organFileResults);
        }

        for (int i = 0; i < organFileResults.size(); i++) {
            System.out.println(organFileResults.get(i).getId());
            Long fileId = organFileResults.get(i).getId();
            String fileUrl = fileUploadMgr.generatePrivUrl(organFileResults.get(i).getFileUrl());
            organFileResults.get(i).setFileUrl(fileUrl);
        }

        return BaseResult.success(organFileResults);
    }

    /**
     * 根据企业userId获取企业文件列表
     */
    @Loggable
    @RequestMapping(value = "get_organ_files", method = RequestMethod.POST)
    public BaseResult getOrganFiles(Long profileId) throws BaseAppException {
        Long userId = UserUtil.getLoginUserId();
        List<OrganFileResult> result = orgFileService.queryFilesByUserIdAndProfileId(userId, profileId);

        if (result == null) {
            return BaseResult.success(result);
        }

        for (int i = 0; i < result.size(); i++) {
            System.out.println(result.get(i).getId());
            Long fileId = result.get(i).getId();
            String fileUrl = fileUploadMgr.generatePrivUrl(result.get(i).getFileUrl());
            result.get(i).setFileUrl(fileUrl);
        }

        Map<String, OrganFileResult> resultMap =  new HashMap<>();

        for (OrganFileResult organFileResult : result) {
            resultMap.put(organFileResult.getFileType(), organFileResult);
        }

        return BaseResult.success(resultMap);
    }

    /**
     * 根据企业userId和fileType获取企业文件
     */
    @Loggable
    @RequestMapping(value = "get_company_file", method = RequestMethod.POST)
    public BaseResult getCompanyFile(String fileType, Long profileId) throws BaseAppException {
        Long userId = UserUtil.getLoginUserId();

        OrgFile orgFile = orgFileService.getOrgFileByUserIdAndFileTypeAndProfileId(userId, fileType, profileId);

        if (orgFile == null) {
            return BaseResult.success(orgFile);
        }

        orgFile.setFileUrl(fileUploadMgr.generatePrivUrl(orgFile.getFileUrl()));

        return BaseResult.success(orgFile);
    }

    /**
     * 获取系统默认的上传token
     *
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "token", method = RequestMethod.GET)
    public BaseResult getUploadToken(@RequestParam(name = "suffix", defaultValue = "") String suffix,
                                     @RequestParam(name = "bucketId", defaultValue = "2") Long bucketId) throws BaseAppException {
        return BaseResult.success(fileUploadMgr.getUploadToken(suffix, bucketId));
    }

    /**
     * 获取私有文件下载链接
     *
     * @param fileId
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "priv/{fileId}", method = RequestMethod.GET)
    public BaseResult queryPrivUrl(@PathVariable(name = "fileId") Long fileId) throws BaseAppException {
        return BaseResult.success(fileUploadMgr.generatePrivUrl(fileId));
    }

    /**
     * 保存上传的信息
     *
     * @return
     */
    @Loggable
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public BaseResult saveFileInfo(OrganFileResult organFileResult) throws BaseAppException {
        return BaseResult.success(orgFileService.save(organFileResult));
    }

    /**
     * 更新文件信息
     *
     * @param orgFile
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "update", method = RequestMethod.POST)
    public BaseResult updateFileInfo(OrgFile orgFile) throws BaseAppException {
        return BaseResult.success(orgFileService.update(orgFile));
    }

    /**
     * 删除资源
     *
     * @param id
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)
    public BaseResult deleteFile(@PathVariable(name = "id") Long id) throws BaseAppException {

        orgFileService.delete(id);

        return BaseResult.success();
    }

    /**
     * 分页获取文件资源
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Loggable
    @RequestMapping(value = "files", method = RequestMethod.GET)
    public BaseResult queryFiles(@RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws BaseAppException {
        return BaseResult.success(orgFileService.queryFiles(pageIndex, pageSize));
    }

    /**
     * 分页获取图片资源
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @Loggable
    @RequestMapping(value = "pictures", method = RequestMethod.GET)
    public BaseResult queryPictures(@RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws BaseAppException {
        return BaseResult.success(orgFileService.queryPictures(pageIndex, pageSize));
    }


    /**
     * 获取文件总数
     *
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "filesCount", method = RequestMethod.GET)
    public BaseResult queryFilesCount() throws BaseAppException {
        return BaseResult.success(orgFileService.queryFilesCount());
    }

    /**
     * 获取图片总数
     *
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "picturesCount", method = RequestMethod.GET)
    public BaseResult queryPicturesCount() throws BaseAppException {

        return BaseResult.success(orgFileService.queryPictureCount());
    }

    /**
     * 通过文件名查询文件记录
     *
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "searchFile", method = RequestMethod.GET)
    public BaseResult searchFile(@RequestParam(name = "fileName") String fileName,
                                 @RequestParam(name = "pageIndex", defaultValue = "1") Integer pageIndex,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) throws BaseAppException {
        return BaseResult.success(orgFileService.queryFilesByFileName(fileName, pageIndex, pageSize));
    }

    /**
     * 通过文件名查询文件记录条数
     *
     * @return
     * @throws BaseAppException
     */
    @Loggable
    @RequestMapping(value = "searchFileCount", method = RequestMethod.GET)
    public BaseResult searchFile(@RequestParam(name = "fileName") String fileName) throws BaseAppException {
        return BaseResult.success(orgFileService.queryCountByFileName(fileName));
    }
}
